#include "explorerbar.h"
#include "ui_explorerbar.h"

#include "utils.h"

ExplorerBar::ExplorerBar(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::ExplorerBar)
{
    ui->setupUi(this);
    setObjectName("ExplorerBar");

    layout()->setMargin(1);

    model = new QFileSystemModel(this);
    model->setRootPath("");
    model->setNameFilterDisables(false);

    ui->tvDirs->setModel(model);
    ui->tvDirs->setColumnHidden(1, true);
    ui->tvDirs->setColumnHidden(2, true);
    ui->tvDirs->setColumnHidden(3, true);

    ui->tvDirs->setSortingEnabled(true);
    ui->tvDirs->sortByColumn(0, Qt::AscendingOrder);

    connect(ui->tvDirs->selectionModel(), SIGNAL(currentRowChanged(QModelIndex,QModelIndex)),
            this, SLOT(currentRowChanged(QModelIndex,QModelIndex)));

    ui->tvDirs->setMouseTracking(true);
    connect(ui->tvDirs, SIGNAL(entered(QModelIndex)), this, SLOT(highlighted(QModelIndex)));

    connect(ui->tbSynchReq, SIGNAL(clicked()), this, SIGNAL(synchFileRequest()));


//    QCompleter *comp = new QCompleter(this);
//    //comp->setCompletionMode();
//    ui->leFilter->setCompleter(comp);


    ui->tvDirs->addAction(ui->actionOpen);
    QAction *sep = new QAction(this); sep->setSeparator(true);
    ui->tvDirs->addAction(sep);
    ui->tvDirs->addAction(ui->actionCopyPath);
    ui->tvDirs->addAction(ui->actionCopyName);
}

ExplorerBar::~ExplorerBar()
{
    delete ui;
}

void ExplorerBar::changeEvent(QEvent *e)
{
    QWidget::changeEvent(e);
    switch (e->type()) {
    case QEvent::LanguageChange:
        ui->retranslateUi(this);
        break;
    default:
        break;
    }
}

void ExplorerBar::readConfig(QSettings &set)
{
  QModelIndex index = model->index(set.value("ExplorerPath").toString());
  ui->tvDirs->setCurrentIndex(index);
  QTimer::singleShot(100, this, SLOT(doVisibleCurrent()));

  ui->tbSynch->setChecked(set.value("ExplorerSynch", true).toBool());
  ui->tbFixCollapse->setChecked(set.value("ExplorerAutoCollapse", true).toBool());
}

void ExplorerBar::writeConfig(QSettings &set)
{
  set.setValue("ExplorerPath", model->filePath(ui->tvDirs->currentIndex()));
  set.setValue("ExplorerSynch", ui->tbSynch->isChecked());
  set.setValue("ExplorerAutoCollapse", ui->tbFixCollapse->isChecked());
}

void ExplorerBar::on_tvDirs_activated(const QModelIndex & index)
{
  if (model->isDir(index))
    return;

  emit fileClicked(model->filePath(index));
}

void ExplorerBar::navigate(const QString &name)
{
  QModelIndex index = model->index(name);
  if (index.isValid())
  {
    ui->tvDirs->setCurrentIndex(index);

    if (ui->tbFixCollapse->isChecked())
      QTimer::singleShot(100, this, SLOT(on_tbAutoCollapse_clicked()));
    else
      QTimer::singleShot(100, this, SLOT(doVisibleCurrent()));
    //qDebug() << ui->tvDirs->visualRect(index);
  }
}

void ExplorerBar::synchronizeIfNeeded(const QString &name)
{
  if (ui->tbSynch->isChecked())
    navigate(name);
}

void ExplorerBar::doVisibleCurrent()
{
  static bool count = false;

  if (count)
  {
    count = false;
    QRect r = ui->tvDirs->visualRect(ui->tvDirs->currentIndex());
    if (r.isNull() || r.top() < 0 || r.top() > ui->tvDirs->height())
    {}
    else
    {
      //on_leFilter_textChanged(ui->leFilter->text());
      model->setNameFilters(ui->leFilter->text().split(";", QString::SkipEmptyParts));
      return;
    }
  }

  ui->tvDirs->scrollTo(ui->tvDirs->currentIndex(), QAbstractItemView::PositionAtCenter);
  QRect r = ui->tvDirs->visualRect(ui->tvDirs->currentIndex());
  if (r.isNull() || r.top() < 0 || r.top() > ui->tvDirs->height())
    count = false;
  else
    count = true;

  QTimer::singleShot(200, this, SLOT(doVisibleCurrent()));
}

void ExplorerBar::currentRowChanged(const QModelIndex & current, const QModelIndex & )
{
  emit fileCurrent(Utils::normalizeFilename(model->filePath(current)));
}

void ExplorerBar::highlighted(const QModelIndex & current)
{
  emit fileCurrent(Utils::normalizeFilename(model->filePath(current)));
}


//void ExplorerBar::on_tbExpandAll_clicked()
//{
//  //QTimer::singleShot(0, ui->tvDirs, SLOT(expandAll()));
//}
//
//void ExplorerBar::on_tbCollapseAll_clicked()
//{
//  //QTimer::singleShot(0, ui->tvDirs, SLOT(collapseAll()));
//}

void ExplorerBar::on_tbAutoCollapse_clicked()
{
  QModelIndex idx = ui->tvDirs->currentIndex();
  ui->tvDirs->collapseAll();

  while (idx.isValid())
  {
    ui->tvDirs->expand(idx);
    idx = idx.parent();
  }

  doVisibleCurrent();
}

void ExplorerBar::on_tbPickItem_clicked()
{
//  QString name = QInputDialog::getText(this, tr("Pick Item"),
//                                       tr("Path to file/directory to browse for:"),
//                                       QLineEdit::Normal,
//                                       model->filePath(ui->tvDirs->currentIndex())
//                                       );
//  if (!name.isEmpty())
//    navigate(name);

  QString name = QFileDialog::getExistingDirectory(
      this, tr("Path to the directory to browse for:"),
      model->filePath(ui->tvDirs->currentIndex()));

  if (!name.isEmpty())
  {
    ui->leDir->setText(name);
    ui->leDir->selectAll();
    navigate(name);
  }
}

void ExplorerBar::on_leDir_returnPressed()
{
  QString name = ui->leDir->text();

  if (!name.isEmpty())
      navigate(name);
}

void ExplorerBar::on_leFilter_textChanged ( const QString & text )
{
  model->setNameFilters(text.split(";", QString::SkipEmptyParts));

  QTimer::singleShot(100, this, SLOT(doVisibleCurrent()));
}

void ExplorerBar::on_actionOpen_triggered()
{
  on_tvDirs_activated(ui->tvDirs->currentIndex());
}

void ExplorerBar::on_actionCopyPath_triggered()
{
  QString name(model->filePath(ui->tvDirs->currentIndex()));
  if (!name.isEmpty())
  {
    QApplication::clipboard()->setText(
        Utils::normalizeFilename(name)
        );
  }
}

void ExplorerBar::on_actionCopyName_triggered()
{
  QString name(model->filePath(ui->tvDirs->currentIndex()));
  if (!name.isEmpty())
  {
    QApplication::clipboard()->setText(
        Utils::normalizeFilename(QFileInfo(name).fileName())
        );
  }
}
